﻿// --------------------------------
// <copyright file="ProductService.cs" company="TRONSoft">
//     Copyright (c) TRONSoft.
// </copyright>
// <license>
//   This source code is subject to terms and conditions of the Microsoft
//   Public License. A copy of the license can be found in the License.html
//   file at the root of this distribution. If you cannot locate the
//   Microsoft Public License, please send an email to dlr@microsoft.com.
//   By using this source code in any fashion, you are agreeing to be bound 
//   by the terms of the Microsoft Public License. You must not remove this
//   notice, or any other, from this software.
// </license>
// <author>Tron</author>
// ---------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace Actucal
{
    public static class ProductsService
    {
        private static Product currentProduct;
        private static List<Product> products = new List<Product>();

        static ProductsService()
        {
            string path = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "bin");
            if (File.Exists(path))
            {
                products = Tools.LoadDataAsBinary<List<Product>>(path) ?? new List<Product>();
            }
        }

        public static List<Product> Products
        {
            get { return products; }
            set
            {
                if (null == value)
                    products = new List<Product>();

                products = value;

                if (products.Count > 0)
                {
                    currentProduct = products[0];
                }
            }
        }

        public static Product CurrentProduct
        {
            get { return currentProduct; }
            set
            {
                if (null == value)
                    throw new ArgumentNullException("value");

                currentProduct = value;

                OnCurrentProductChanged(new ArgumentEventArgs<Product>(value));
            }
        }

        public static event EventHandler<ArgumentEventArgs<Product>> CurrentProductChanged;

        public static Product GetProduct(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            return products.Find(delegate(Product product) { return product.Name == name; });
        }

        private static void OnCurrentProductChanged(ArgumentEventArgs<Product> e)
        {
            if (null != CurrentProductChanged)
                CurrentProductChanged(null, e);
        }
    }
}